package cn.tedu.knows.resource.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
// 当前项目已经设置了一个前置的默认路径/image
// 访问这个控制器的路径/image/file
@RequestMapping("/file")
@Slf4j
// 跨域注解
@CrossOrigin
public class ImageController {
    // 从 application.properties文件中获取配置的信息
    @Value("${knows.resource.path}")
    private File resourcePath;

    @Value("${knows.resource.host}")
    private String resourceHost;

    @PostMapping
    public String upload(MultipartFile imageFile) throws IOException {
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        //实例化要上传的文件夹对象
        //F:/upload/2021/12/03
        File folder = new File(resourcePath, path);
        //创建文件夹
        folder.mkdirs();
        String filename = imageFile.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + ext;
        //确定随机文件名
        File file = new File(folder, name);
        log.debug("文件上传到:{}", file.getAbsoluteFile());
        //执行上传操作
        imageFile.transferTo(file);
        String url = resourceHost + "/" + path + "/" + name;
        log.debug("可显示图片的url:{}", url);
        //返回url,以实现图片的回显
        return url;
    }
}
